package org.dromara.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.LzshBusinessInfo;
import org.dromara.business.domain.LzshBusinessInfoDataTotal;
import org.dromara.business.domain.bo.LzshBusinessInfoBo;
import org.dromara.business.domain.vo.LzshBusinessInfoVo;
import org.dromara.business.mapper.LzshBusinessInfoMapper;
import org.dromara.business.service.ILzshBusinessInfoService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * business信息Service业务层处理
 *
 * @author sxl
 * @date 2024-08-19
 */
@RequiredArgsConstructor
@Service
public class BusinessinfoServiceImpl implements ILzshBusinessInfoService {

    private final LzshBusinessInfoMapper baseMapper;


    /**
     * 查询business信息
     *
     * @param id 主键
     * @return business信息
     */
    @Override
    public LzshBusinessInfoVo queryById(Long id){
        return baseMapper.selectById(id);
    }

    /**
     * 分页查询business信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return business信息分页列表
     */
    @Override
    public TableDataInfo<LzshBusinessInfoVo> queryPageList(LzshBusinessInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<LzshBusinessInfo> lqw = buildQueryWrapper(bo);
//        Page<LzshBusinessInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //返回自定义查询的
        pageQuery.setPageNum((pageQuery.getPageNum()-1)*pageQuery.getPageSize());
        List<LzshBusinessInfoVo> result = baseMapper.selectListVo(bo,pageQuery);
        TableDataInfo<LzshBusinessInfoVo> build = TableDataInfo.build(result);
        //获取总数
        List<LzshBusinessInfo> all = baseMapper.selectList(lqw);
        build.setTotal(all.size());
        build.setMsg("查询成功");
        return build;
    }

    /**
     * 查询符合条件的business信息列表
     *
     * @param bo 查询条件
     * @return business信息列表
     */
    @Override
    public List<LzshBusinessInfoVo> queryList(LzshBusinessInfoBo bo) {
        LambdaQueryWrapper<LzshBusinessInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<LzshBusinessInfo> buildQueryWrapper(LzshBusinessInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LzshBusinessInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTemplateId() != null, LzshBusinessInfo::getTemplateId, bo.getTemplateId());
        lqw.eq(bo.getCreateBy() != null, LzshBusinessInfo::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank((CharSequence) bo.getTemplate()), LzshBusinessInfo::getTemplate, bo.getTemplate());
        lqw.eq(StringUtils.isNotBlank((CharSequence) bo.getUserInfo()), LzshBusinessInfo::getUserInfo, bo.getUserInfo());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessAddress()), LzshBusinessInfo::getBusinessAddress, bo.getBusinessAddress());
        lqw.eq(bo.getLatitude() != null, LzshBusinessInfo::getLatitude, bo.getLatitude());
        lqw.eq(bo.getLongitude() != null, LzshBusinessInfo::getLongitude, bo.getLongitude());
        lqw.eq(StringUtils.isNotBlank((CharSequence) bo.getOldPlans()), LzshBusinessInfo::getOldPlans, bo.getOldPlans());
        lqw.eq(StringUtils.isNotBlank((CharSequence) bo.getNewPlans()), LzshBusinessInfo::getNewPlans, bo.getNewPlans());

        return lqw;
    }

    /**
     * 新增business信息
     *
     * @param bo business信息
     * @return 是否新增成功
     */
    @Override
    public LzshBusinessInfoVo insertByBo(LzshBusinessInfoBo bo) {
        LzshBusinessInfo add = MapstructUtils.convert(bo, LzshBusinessInfo.class);
        add.setTenantId("000000");
        validEntityBeforeSave(add);
        //获取模板对象的数据，然后转为JSON对象
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            return baseMapper.selectById(bo.getId());
        }
        return null;
    }

    /**
     * 修改business信息
     *
     * @param bo business信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(LzshBusinessInfoBo bo) {
        LzshBusinessInfo update = MapstructUtils.convert(bo, LzshBusinessInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(LzshBusinessInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除business信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 按照年份返回当年的每个月的填写数量
     * @param year 年份
     * @return
     */
    @Override
    public  Map<String,List<LzshBusinessInfoDataTotal.totalData>> getMonthNum(String year) {
        List<LzshBusinessInfoDataTotal.totalData> listData = new ArrayList<>();
        LzshBusinessInfoDataTotal lzshBusinessInfoDataTotal = new LzshBusinessInfoDataTotal();
        //按照每年的12月份遍历得到每个月对应的数据
        for (int i = 0; i < 12; i++) {
            String month = String.format("%02d", i + 1); //月份
            //根据年份和月份查询数据
            List<LzshBusinessInfo> list = baseMapper.selectList(Wrappers.<LzshBusinessInfo>lambdaQuery()
                    .apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", year + "-" + month));
            //将数据转换为JSON对象
            LzshBusinessInfoDataTotal.totalData data = new LzshBusinessInfoDataTotal.totalData();
            data.setProduct(month);
            data.setData1((long) list.size());
            listData.add(data);
        }
        lzshBusinessInfoDataTotal.setSource(listData);
        Map<String,List<LzshBusinessInfoDataTotal.totalData>> map = new HashMap<>();
        map.put("source",lzshBusinessInfoDataTotal.getSource());
        return map;

    }

    @Override
    public Map<String, List<LzshBusinessInfoDataTotal.totalData2>> getCityNum() {
        Map<String, Integer> cityMap = new HashMap<>();
        List<LzshBusinessInfo> data = baseMapper.selectList();
        for (LzshBusinessInfo item : data) {
            String city =  getCity(item.getBusinessAddress());
            if (cityMap.containsKey(city)) {
                cityMap.put(city, cityMap.getOrDefault(city, 0) + 1);
            } else {
                // 如果 cityMap 不包含该城市名，则将其加入 map，初始值为 1（因为是第一次出现）
                cityMap.put(city, 1);
            }
        }
        List<LzshBusinessInfoDataTotal.totalData2> listData = new ArrayList<>();
        // 遍历 cityMap 的每个条目
        for (Map.Entry<String, Integer> entry : cityMap.entrySet()) {
            String city = entry.getKey(); // 获取城市名（键）
            Integer count = entry.getValue(); // 获取该城市的业务数量（值）
            LzshBusinessInfoDataTotal.totalData2 data2 = new LzshBusinessInfoDataTotal.totalData2();
            data2.setName(city);
            data2.setValue(Long.valueOf(count));
            listData.add(data2);
        }
        Map<String, List<LzshBusinessInfoDataTotal.totalData2>> map = new HashMap<>();
        map.put("map",listData);
        return map;
    }

    public static String getCity(String address) {
        int startIndex = address.indexOf("自治区") + 3; // "自治区"的长度为3
        int endIndex = address.indexOf("市", startIndex) + 1; // 找到"市"并包含"市"字符
        // 截取地级市名称
        if (startIndex != -1 && endIndex != -1) {
            return address.substring(startIndex, endIndex);
        }
        return "";
    }
}
